<script>
import './anima.scss';
import { isPc } from '@/uilts/routes';

//动画的逻辑， 让页面透明度为0， 然后慢慢显示。
// 在移除时，添加动画，再移除动画。

let pageAnimation = false;
let pageAnimationName = '';
let pageBefore = '';
let pageAfter = '';
let pageIn = 'no';
let pageOut = 'no';
let isBack = false;

const hide = (callback) => {
	pageBefore = isBack ? pageAnimationName + '-back-enter' : pageAnimationName + '-enter';
	pageAfter = isBack ? pageAnimationName + '-back-leave' : pageAnimationName + '-leave';
	isBack = false;
	pageAnimationName = '';
	setTimeout(() => {
		const classList = document.querySelector('uni-page').classList;
		classList.add(pageOut, pageBefore);
		classList.remove('page-show');
		setTimeout(() => {
			classList.remove(pageOut, pageBefore);
			callback && callback();
		}, 300);
	}, 20);
};

const show = () => {
	let pagePath = window.location.pathname;
	const classList = document.querySelector('uni-page').classList;

	const pageOpts = PAGES[pagePath];
	pageAnimation = true;
	if (pageOpts && pageOpts.openAnima) {
		if (pageOpts.animaName) {
			pageAnimationName = pageOpts.animaName;
		}
		if (pageOpts.pageIn && pageOpts.pageIn == false) {
			pageIn = 'no';
		} else {
			pageIn = 'page-animation-enter';
		}
		if (pageOpts.pageOut && pageOpts.pageOut == false) {
			pageOut = 'no';
		} else {
			pageOut = 'page-animation-leave';
		}
	}

	if (pagePath == '/' || pageAnimation != true || !pageBefore) {
		classList.add('page-show');
		return false;
	}
	classList.add(pageBefore);
	setTimeout(() => {
		classList.add(pageIn, pageAfter, 'page-show');
		setTimeout(() => {
			classList.remove(pageIn, pageBefore, pageAfter);
		}, 300);
	}, 20);
	pageAnimation = false;
};

export default {
	onLaunch: function () {
		if (isPc.value) return
		window.addEventListener(
			'popstate',
			(e) => {
				isBack = true;
			},
			false
		);
		show();
		//主要是监听了这里
		this.$router.beforeEach((toPage, fromPage, next) => {
			hide(next);
		});
		this.$router.afterEach(() => {
			setTimeout(show, 50);
		});
	},
};
</script>
